<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JWT Test</title>
</head>
<body>
<h1>Test User API with JWT</h1>

<!-- 登录表单 -->
<div>
    <h2>Login</h2>
    <label for="username">Username:</label>
    <input type="text" id="username" placeholder="Enter username"><br><br>
    <label for="password">Password:</label>
    <input type="password" id="password" placeholder="Enter password"><br><br>
    <button onclick="login()">Login</button>
</div>

<hr>

<!-- 用户信息 -->
<div>
    <h2>Get User Info</h2>
    <label for="getUsername">Username:</label>
    <input type="text" id="getUsername" placeholder="Enter username to fetch"><br><br>
    <button onclick="getUserInfo()">Get User Info</button>
</div>

<hr>

<!-- 显示用户信息 -->
<div>
    <h3>User Info</h3>
    <pre id="userInfo"></pre>
</div>

<script>
    let jwtToken = "";  // 用于存储登录后返回的 JWT Token

    // 用户登录
    function login() {
        const username = document.getElementById('username').value;
        const password = document.getElementById('password').value;

        const loginData = {
            username: username,
            password: password
        };

        fetch('http://localhost:8080/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.token) {
                    jwtToken = data.token;
                    alert('Login successful! Token: ' + jwtToken);
                } else {
                    alert('Login failed: ' + data.message);
                }
            })
            .catch(error => console.error('Error:', error));
    }

    // 获取用户信息
    function getUserInfo() {
        const getUsername = document.getElementById('getUsername').value;
        if (!jwtToken) {
            alert('Please log in first!');
            return;
        }

        fetch(`http://localhost:8080/users/${getUsername}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${jwtToken}`
            }
        })
            .then(response => {
                if (response.status === 200) {
                    return response.json();
                } else if (response.status === 401) {
                    alert('Unauthorized: Token expired or invalid');
                    return;
                } else {
                    alert('User not found');
                    return;
                }
            })
            .then(data => {
                if (data) {
                    document.getElementById('userInfo').textContent = JSON.stringify(data, null, 2);
                }
            })
            .catch(error => console.error('Error:', error));
    }
</script>
</body>
</html>
